<?php

class model_install extends model
{


	public function save_config($obj, $file)
	{
		$vars = get_object_vars($obj);

		$buf = "<?php\r\n";
		$buf .= 'class '.get_class($obj)."\r\n";
		$buf .= "{\r\n";

		foreach($vars as $key=>$val)
		{
			$buf .= '  public $'.$key.' = \''.$val.'\';' . "\r\n";
		}
		$buf .= "}\r\n";
		$buf .= '?>';
		
		file_put_contents( $file, $buf);
	}


	public function install()
	{
		$files = array();

		$files[] = BONE_ADMIN.DS.'apps'.DS.'content'.DS.'install.sql';
		$files[] = BONE_ADMIN.DS.'apps'.DS.'content'.DS.'init.sql';

		$files[] = BONE_ADMIN.DS.'apps'.DS.'menu'.DS.'install.sql';
		$files[] = BONE_ADMIN.DS.'apps'.DS.'menu'.DS.'init.sql';

		$files[] = BONE_ADMIN.DS.'apps'.DS.'user'.DS.'install.sql';
		$files[] = BONE_ADMIN.DS.'apps'.DS.'user'.DS.'init.sql';
		
		$db = bone::get_db();
		foreach($files as $file)
		{
			if(file_exists($file))
			{
				$sqls = $this->split_sql( file_get_contents($file) );
				foreach($sqls as $sql)
				{
					$db->execute( $sql );
				}
			}
		}
	}


	private function split_sql( $sql )
	{
		$start = 0;
		$open = false;
		$open_char = '';
		$end = strlen($sql);
		$sqls = array();
		for($i=0;$i<$end;$i++) {
			$current = substr($sql,$i,1);
			if(($current == '"' || $current == '\'')) {
				$n = 2;
				while(substr($sql,$i - $n + 1, 1) == '\\' && $n < $i) {
					$n ++;
				}
				if($n%2==0) {
					if ($open) {
						if($current == $open_char) {
							$open = false;
							$open_char = '';
						}
					} else {
						$open = true;
						$open_char = $current;
					}
				}
			}
			if(($current == ';' && !$open)|| $i == $end - 1) {
				$sqls[] = substr($sql, $start, ($i - $start + 1));
				$start = $i + 1;
			}
		}

		return $sqls;
	}

}
?>